package org.wheel.module.core.exception;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serial;
import java.io.StringWriter;

/**
 * 封装的异常
 *
 * @author lanjf2000
 * @Date 2020/10/27
 */
@Data
@EqualsAndHashCode(callSuper=false)
@AllArgsConstructor
@NoArgsConstructor
public class NormalException extends RuntimeException {

	@Serial
    private static final long serialVersionUID = 1L;

	private Integer code;

    private String message;
    
    private String i18nMessage;
    
    public NormalException(Integer code, String message) {
        this.code=code;
        this.message=message;
        this.i18nMessage=null;
    }
    
    public NormalException(ServiceExceptionEnum exceptionEnum) {
    	this.code = exceptionEnum.getCode();
    	this.message = exceptionEnum.getMessage();
    	this.i18nMessage = exceptionEnum.getI18nMessage();
    }
    
    /**
     * 使用StringWriter将异常堆栈中的信息转换为String字符串<br>
     * 这个方法可以将Exception对象堆栈中的信息转换为String字符串返回，以供后续处理。
     * @param e 异常信息对象
     * @return 异常信息字符串
     */
    public static String getErrorInfoFromException(Exception e) {
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            return sw.toString();
        } catch (Exception e2) {
            return "ErrorInfoFromException";
        } finally {
            try {
                if (sw != null) {
                    sw.close();
                }
                if (pw != null) {
                    pw.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}
